var materialArray;
var baseUrl = "/weixin/";
var table;
//相关业务逻辑
$(function () {
	page.bindTag();
	page.getAllSearchWhere();
	scheduling.bind();
});

var page = { //页面总变量 
	pageOrderId: '',
	orderList: [],
	materialSort: 0,
	searchType: "",
	procedureSumCount: 0,
	aleradySaveData: [],
	bindTag: function () {
		$("#orderId").unbind("kepup");
		
		/**
		 *  查询已保存的订单工序
		 */
		$("#queryBtn").bind("click", function () {
			var orderId = $("#orderId").val().trim();
			if (orderId == '') {
				layAlert("请输入或选择订单编号");
				return false;
			}
			page.getAlreadySaveProcedure(orderId);
		});
	},
	getAlreadySaveProcedure: function (orderId) {
		page.pageOrderId = orderId;
		ajaxUtil.ajaxRuquest(baseUrl + "thirdPartyView/getAlreadySaveProcedure", {
			"orderId": orderId
		}, function (data) {
			page.aleradySaveData = data;
			if (data.length <= 0) {
				layAlert("该订单没有设置工序");
				return false;
			}
			/**
			 * 循环遍历物料类型
			 */
			var sumCount = 0;
			var $html = $('<div></div>');
			for (var i = 0; i < data.length; i++) {
				var obj = data[i];
				var procedureList = obj.procedureList;
				var materialType = obj.materialType;
				var color = procedureList[0].color;
				var $item = $('<div class="pro-item"></div>');
				$html.append($item);

				$item.append(`
						<div class="item-title material" style="color:${color};" materialType="${materialType}" color="${color}">
							<span>${materialType}</span>
							<span>${procedureList.length}</span>
						</div>
					`);
				sumCount = sumCount + procedureList.length;
				for (var j = 0; j < procedureList.length; j++) {
					var pro = procedureList[j];
					var proColor = pro.color;
					var otherMaching = '';
					if (pro.otherMaching !== '') {
						otherMaching = pro.otherMaching;
					}

					var proText = [pro.workShopName, pro.procedureName];
					if (otherMaching !== '') {
						proText.push(otherMaching);
					}

					$item.append(`
						<div style="color:${proColor};" class="procedureFont" color="${proColor}" 
							materialType="${materialType}" procedureId="${pro.procedureId}" otherMaching="${otherMaching}">
							${proText.join('-')}
						</div>
					`);
				}
			}
			page.procedureSumCount = sumCount;
			$(".materialProcedure").html($html.html());
			$("#editMaterialProcedureBtn").removeClass("hidden");
			$("#autoSchedulingBtn").removeClass("hidden");
			page.drawFlow();
		});
		page.searchType = "query";
	},
	getAllSearchWhere: function () { /**获取所有筛选条件*/
		ajaxUtil.ajaxRuquestNoQuan(baseUrl + 'thirdPartyView/getAllOrderSearchWhere', null, function (data) {
			page.orderList = data;
			page.setView(page.orderList);
		});
	},
	setView: function (data) {
		var html = ""
		for (var i = 0; i < data.length; i++) {
			html += "<option value='" + data[i].orderId + "' style='display:none'>" + data[i].companyOrderId + " &nbsp;&nbsp;&nbsp;&nbsp;" + data[i].factoryId + " &nbsp;&nbsp;&nbsp;&nbsp;" + data[i].coustomOrderId + "&nbsp;&nbsp;&nbsp;&nbsp;" + data[i].coustomId + "</option>"
		}
		$("#detailList").html(html);
	},
	drawFlow: function () {
		var $content = $('.pro-content');
		var $pro = $content.find('.materialProcedure');

		var $proItems = $pro.find('.pro-item');
		var proItems = [];
		for (var i = 0; i < $proItems.length; i++) {
			var $proItem = $($proItems[i]);
			var $processes = $proItem.find('>div');
			var $proTitle = $($processes[0]);
			var obj = {
				color: $proTitle.attr('color'),
				$titleEl: $proTitle,
				index: i
			};

			var processList = [];
			var len = $processes.length;
			for (var j = 0; j < len; j++) {
				var $process = $($processes[j]);
				if (j === len - 1) {
					obj.$lastEl = $process
				}
				if (j === 0) {
					continue;
				}

				var processObj = {
					color: $process.attr('color'),
					$el: $process
				};
				var otherMaching = $process.attr('othermaching');
				if (otherMaching !== '') {
					processObj.otherMaching = otherMaching;
				}
				processList.push(processObj);
			}
			obj.processList = processList;
			proItems.push(obj);
		}

		var drawItems = this.getDrawItems(proItems);
		var $flow = $content.find('.materialFlow');
		var width = $pro.width()
		var height = $pro.height();
		$flow.attr('width', width);
		$flow.attr('height', height);
		this.drawFlowLine($flow[0], drawItems, width, height);
	},
	getDrawItems: function (proItems) {
		var drawItems = [];
		var self = this;
		for (var i = proItems.length - 2; i >= 0; i--) {
			var proItem = proItems[i];
			var processList = proItem.processList;
			var usedColor = [];
			for (var j = 0; j < processList.length; j += addIndex) {
				var processObj = processList[j];
				var color = processObj.color;
				var option = this.checkCanDraw(processList, j, usedColor);
				var addIndex = option.sameProcessLength;

				if (!option.canDraw) {
					continue;
				}

				var sameIndex = _.findIndex(proItems, function (obj, index) {
					if (index <= i) {
						return false;
					}
					return obj.color === color;
				});
				if (sameIndex === -1) {
					continue;
				}
				var sameItem = proItems[sameIndex];
				var $to = processObj.$el;
				var $form = sameItem.$lastEl;

				var rangeItems = proItems.slice(i + 1, sameIndex + 1);
				var maxRangeItem = _.maxBy(rangeItems, function (item) {
					return self.getElTop(item.$lastEl);
				});

				var hasSame;
				if (sameIndex === i + 1) {
					hasSame = false;
				} else {
					hasSame = maxRangeItem.index === sameIndex;
				}

				var top = this.getElTop(maxRangeItem.$lastEl);
				var toTop = this.getElTop($to);
				var sameTop;
				if (hasSame) {
					if (top > toTop) {
						sameTop = top;
					}
				} else {
					if (top >= toTop) {
						sameTop = top + maxRangeItem.$lastEl.height();
					}
				}

				if (sameTop !== undefined) {
					if (sameTop - toTop > 0) {
						$to.css('margin-top', `${sameTop - toTop}px`);
						$to.addClass('has-same-process');
						var $formProcess;
						if (j === 0) {
							$formProcess = proItem.$titleEl;
						} else {
							$formProcess = processList[j - 1].$el;
						}
						drawItems.push({
							form: $formProcess,
							to: $to,
							type: 'process'
						});
					}
				}

				drawItems.push({
					form: $form,
					to: $to,
					type: 'item'
				});
			}
		}
		return drawItems;
	},

	checkCanDraw: function (processList, index, usedColor) {
		var color = processList[index].color;
		var processes = [];

		for (var i = index; i < processList.length; i++) {
			var processObj = processList[i];
			if (color === processObj.color) {
				processes.push(processObj);
			} else {
				break;
			}
		}

		var processObj = _.find(processes, 'otherMaching');
		var canDraw;
		if (processObj !== undefined) {
			canDraw = true;
		} else {
			if (usedColor.indexOf(color) === -1) {
				canDraw = true;
			} else {
				canDraw = false;
			}
		}

		if (canDraw) {
			if (processes[0].otherMaching === undefined) {
				usedColor.push(color);
			}
		}

		return {
			sameProcessLength: processes.length,
			canDraw: canDraw
		};
	},

	drawFlowLine: function (el, drawItems, width, height) {
		var ctx = el.getContext("2d");
		ctx.lineWidth = "2";
		ctx.clearRect(0, 0, width, height);
		for (var i = 0; i < drawItems.length; i++) {
			var drawItem = drawItems[i];
			this.drawLineArrow(ctx, drawItem);
		}
	},

	drawLineArrow: function (ctx, drawItem) {
		var form = drawItem.form;
		var formX = form.position().left;
		var formY = this.getElTop(form);
		var to = drawItem.to;
		var toX = to.position().left;
		var toY = this.getElTop(to);

		var type = drawItem.type;
		var arrawDirection;

		switch (type) {
			case 'item':
				{
					arrawDirection = 'left';
					if (formY === toY) {
						formY += form.outerHeight() / 2;
						toY += to.outerHeight() / 2;
						toX += to.outerWidth();
					} else {
						formX += form.outerWidth() / 2;
						formY += form.outerHeight();
						toX += to.outerWidth();
						toY += to.outerHeight() / 2;
					}
					break;
				}
			case 'process':
				{
					arrawDirection = 'bottom';
					formX += form.outerWidth() / 2;
					formY += form.outerHeight();
					toX += to.outerWidth() / 2;
					break;
				}
		}
		formX = _.round(formX, 0);
		formY = _.round(formY, 0);
		toX = _.round(toX, 0);
		toY = _.round(toY, 0);
		if (arrawDirection !== undefined) {
			ctx.beginPath();
			ctx.moveTo(formX, formY);
			if (formX === toX || formY === toY) {
				ctx.lineTo(toX, toY);
			} else {
				ctx.lineTo(formX, toY);
				ctx.lineTo(toX, toY);
			}
			this.drawArrow(ctx, toX, toY, arrawDirection);
			ctx.stroke();
		}
	},

	drawArrow: function (ctx, x, y, direction) {
		var startX, startY, endX, endY;
		switch (direction) {
			case 'left':
				x += 1;
				startX = endX = x + 10;
				startY = y - 7;
				endY = y + 7;
				break;

			case 'bottom':
				y -= 1;
				startY = endY = y - 10;
				startX = x - 7;
				endX = x + 7;
				break;
		}
		ctx.moveTo(startX, startY);
		ctx.lineTo(x, y);
		ctx.lineTo(endX, endY);
	},

	clearCanvas: function () {
		var $content = $('.pro-content');
		var $pro = $content.find('.materialProcedure');
		var $flow = $content.find('.materialFlow');
		var width = $pro.width()
		var height = $pro.height();
		$flow.attr('width', width);
		$flow.attr('height', height);
		var ctx = $flow[0].getContext("2d");
		ctx.lineWidth = "2";
		ctx.clearRect(0, 0, width, height);
	},

	getElTop: function ($el) {
		var marginTop = $el.outerHeight(true) - $el.outerHeight();
		var top = $el.position().top;
		return top + marginTop;
	}
}

/**
 * 排期
 */
var scheduling = {
	bind: function () {
		$("#autoSchedulingBtn").bind("click", function () {
			scheduling.autoScheduling();
		});
	},
	autoScheduling: function () {
		ajaxUtil.ajaxRuquest(baseUrl + "thirdPartyView/getOrderMaterialParchaseAndInCountTime", {'orderId':page.pageOrderId}, function (purchaseAndInData) {
			page.clearCanvas();
			var data = page.aleradySaveData;
			if (data.length <= 0) {
				layAlert("该订单没有设置工序");
				return false;
			}
			/**
			 * 循环遍历物料类型
			 */
			var sumCount = 0;
			var $html = $('<div></div>');
			for (var i = 0; i < data.length; i++) {
				var obj = data[i];
				var procedureList = obj.procedureList;
				var materialType = obj.materialType;
				var color = procedureList[0].color;
				var dayTime = procedureList[0].dailyWorkingHours == 0.0 ? 28800 : procedureList[0].dailyWorkingHours * 60 * 60;
				var $item = $('<div class="pro-item"></div>');
				$html.append($item);

				$item.append(`
							<div class="item-title material" style="color:${color};" materialType="${materialType}" color="${color}">
								<span>${materialType}</span>
								<span>${procedureList.length}</span>
							</div>
						`);
				
				sumCount = sumCount + procedureList.length;
				/**获取最后一道有时间的工序（按工序的顺序）的顺序**/
				var filterProcedure = _.filter(procedureList, function (o) {
					return o.maxTime != '';
				});
				//如果该物料还未开始生产
				var timeSort = 1000000;
				var time = "";
				if (filterProcedure.length > 0) {
					timeSort = filterProcedure[filterProcedure.length - 1].sort;
				}
				var sumTimes = 0;
				
				/**
				 * 判断采购入库的情况
				 */
				if(purchaseAndInData != null && purchaseAndInData.length > 0){//采购入库都没有
					var array= _.filter(purchaseAndInData, function (o) {
						return o.materialType!=null && o.materialType != '';
					});
					if(array.length<=0){//如果改物料没有采购和入库
						$item.append(`
								<div style="color:${color};" class="procedureFont" color="${color}">
								       采购
								</div>
								<div style="color:${color};" class="procedureFont" color="${color}">
								      入库
								</div>
						`);
					}else{//有采购入库信息
						//设置采购时间
						var dd=array[0];
						$item.append(`
								<div style="color:${color};" class="procedureFont" color="${color}">
							     	采购:  &nbsp;&nbsp;<span style='color:green; float:right;'>${dd.laterPhase.substring(5,11)}
								</div>
						`);
						//如果有入库，设置入库时间
						if(dd.inTime!=null && dd.inTime !=''){
							$item.append(`
									<div style="color:${color};" class="procedureFont" color="${color}">
									         入库:  &nbsp;&nbsp;<span style='color:green; float:right;'>${dd.inTime.substring(5,11)}
									</div>
							`);
						}else{//如果没有入库时间，则预计复期入库
							$item.append(`
									<div style="color:${color};" class="procedureFont" color="${color}">
									         入库:  &nbsp;&nbsp;<span style='color:red; float:right;'>${dd.laterPhase.substring(5,11)}
									</div>
							`);
							
							/**
							 * 如果还未开始生产，则预计生产时间
							 */
							if(filterProcedure.length<=0){
								timeSort=-1;
								var dff=moment(dd.laterPhase.substring(0,11)).diff(moment(echartUtil.GetDateStr(0)),'day');
								if(dff>0){
									sumTimes=sumTimes+ dff*dayTime;
								}
							}
						}
					}
				}else{
					$item.append(`
							<div style="color:${color};" class="procedureFont" color="${color}">
							       采购
							</div>
							<div style="color:${color};" class="procedureFont" color="${color}">
							      入库
							</div>
					`);
				}
				
				
				var beforeTime="";
				for (var j = 0; j < procedureList.length; j++) {

					var pro = procedureList[j];
					var proColor = pro.color;
					var otherMaching = '';
					if (pro.otherMaching !== '') {
						otherMaching = pro.otherMaching;
					}

					var proText = [pro.workShopName, pro.procedureName];
					if (otherMaching !== '') {
						proText.push(otherMaching);
					}

					var color = 'green';
					var maxTime = "";
					//当本道工序就是最后一道报工顺序的时候，时间显示为本道工序最后报工时间
					if (pro.sort <= timeSort) {
						maxTime = pro.maxTime;
					}
					//当本工序在最后报工工序之后的时候
					if (pro.sort > timeSort) {
						var procedureTime = 0;
						if (pro.processingObject == '款') { //如果是调机，只算一次
							procedureTime = pro.procedureWorkTime;
						} else { //否则为订单数*工序作业时间
							procedureTime = pro.procedureWorkTime * pro.orderCount;
						}
						//加上交接时间20分钟(1200秒)
						procedureTime = procedureTime + 1200;
						sumTimes = sumTimes + procedureTime;
						var day = Math.floor(sumTimes / dayTime);
						maxTime = echartUtil.GetDateStr(day);
						var restType = pro.restType;
						if(beforeTime=="" || moment(echartUtil.GetDateStr(0)).diff(moment(beforeTime),'day')>=0){
							beforeTime=echartUtil.GetDateStr(0);
						}
						var dayArray=scheduling.getBetweenDateStr(beforeTime,maxTime);
						var addDay=scheduling.getMonthWorkDay(restType, dayArray);
						if(addDay>0){
							if(addDay%1==0){
								sumTimes=sumTimes+addDay*dayTime;
								day=day+addDay;
								maxTime=echartUtil.GetDateStr(day);
							}else{
								sumTimes = sumTimes + dayTime / 2 +(addDay-1)*dayTime;
								day=Math.floor(sumTimes / dayTime);
								maxTime=echartUtil.GetDateStr(day);
							}
						}
						dayArray=[];
						dayArray.push(maxTime);
						var restDay = scheduling.getMonthWorkDay(restType, dayArray);
						
						if (restDay == 1) {
							//时间加一天
							sumTimes = sumTimes + dayTime;
							maxTime = echartUtil.GetDateStr(day + 1);
							dayArray=[];
							dayArray.push(maxTime);
							//判断时间加一天是否
							restDay = scheduling.getMonthWorkDay(restType, dayArray);
							//如果是休息
							if (restDay == 1) {
								//时间再加一天
								sumTimes = sumTimes + dayTime;
								maxTime = echartUtil.GetDateStr(day + 1);
							}
						} else if (restDay == 0.5) {
							//时间加半天
							sumTimes = sumTimes + dayTime / 2;
							//判断加半天之后时候跨天
							var xx = Math.floor(sumTimes / dayTime);
							if (xx != day) {
								//时间为加半天之后的日期
								maxTime = echartUtil.GetDateStr(xx);
								dayArray=[];
								dayArray.push(maxTime);
								//判断时间加一天是否
								restDay = scheduling.getMonthWorkDay(restType, dayArray);
								if (restDay == 1) {
									sumTimes = sumTimes + dayTime;
									maxTime = echartUtil.GetDateStr(day + 1);
								}
							}
						}
						color = 'red';
					}
					beforeTime=maxTime;


					$item.append(`
							<div style="color:${proColor};" class="procedureFont" color="${proColor}" 
								materialType="${materialType}" procedureId="${pro.procedureId}" otherMaching="${otherMaching}">
								${proText.join('-')} &nbsp;&nbsp;<span style='color:${color}; float:right;'>${maxTime.substring(5,11)}</span> 
							</div>
						`);
				}
			}
			page.procedureSumCount = sumCount;
			$(".materialProcedure").html($html.html());
		});
	},
	/**
	 * lastProcedure 最后报工序工序
	 * sumTimes 生产之后的工序一共要多少秒
	 */
//	getLastTime: function (lastProcedure, sumTimes) {
//
//		//如果没有
//		if (lastProcedure == null || sumTimes == 0) {
//			return "该物料还未开始生产";
//		}
//		//将秒转换为小时,向上取整
//		var hours = Math.ceil(sumTimes / 60 / 60);
//		var day = 0;
//		var date = new Date();
//		//下午则向下取整
//		if (lastProcedure.dailyWorkingHours == 0) {
//			lastProcedure.dailyWorkingHours = 8;
//		}
//		if (date.getHours > 12) {
//			day = Math.floor(hours / lastProcedure.dailyWorkingHours);
//		} else { //上午向上取整
//			day = Math.ceil(hours / lastProcedure.dailyWorkingHours);
//		}
//		/**
//		 * 理论上完成时间
//		 */
//		var endTime = echartUtil.GetDateStr(day);
//		var dayList = scheduling.getBetweenDateStr(echartUtil.GetDateStr(0), endTime);
//		var restDay = scheduling.getMonthWorkDay(lastProcedure.restType, dayList);
//		day = day + restDay;
//		return echartUtil.GetDateStr(day);
//	},
	/*
	 * 获取两日期之间的所有日期
	 */
	getBetweenDateStr: function (start, end) {
		var result = [];
		var startMoment=moment(start);
		var endMoment=moment(end);
		while(startMoment.isSameOrBefore(endMoment,'day')){
			result.push(startMoment.format('YYYY-MM-DD'));
			startMoment.add(1,'day');
		}
		return result;
	},
	/**
	 * 根据休息类型和日期判断当天是否休息
	 */
	getMonthWorkDay: function (restType, days) {
		var restDay = 0; //该区间休息天数
		switch (restType) {
			case 0:
				restDay = 0;
				break; //月休0填
			case 1: //月休一天，默认初一休息
				//如果含有初一，则休息一天
				_.forEach(days, function(day) {
					  if (Number(day.substring(8, 10)) == 1) {
						  restDay = restDay + 1;
					  }
				});
				break;
			case 2: //月休两天
				//如果含有初一，或者含有15，则休息一天
				_.forEach(days, function(day) {
					if (Number(day.substring(8, 10)) == 1 || Number(day.substring(8, 10)) == 15) {
						restDay = restDay + 1;
					}
				});
				break;
			case 3: //月休三天
				//如果含有初一，或者含有10号，20号，则休息一天
				_.forEach(days, function(day) {
					if (Number(day.substring(8, 10)) == 1 || Number(day.substring(8, 10)) == 10 || Number(day.substring(8, 10)) == 20) {
						restDay = restDay + 1;
					}
				});
				break;
			case 4: //周休一天
				//周天休息一天
				_.forEach(days, function(day) {
					if (moment(day).day() == 0) {
						restDay = restDay + 1;
					}
				});
				break;
			case 5: //周休1.5天
				//周天休息一天，周六休息半天
				_.forEach(days, function(day) {
					if (moment(day).day() == 0) {
						restDay = restDay + 1;
					}
					if (moment(day).day() == 6) {
						restDay = restDay + 0.5;
					}
				});
				break;
			case 6: //周休2天
				//周天，周六休息一天
				_.forEach(days, function(day) {
					if (moment(day).day() == 0 || moment(day).day() == 6) {
						restDay = restDay + 1;
					}
				});
				break;
		}
		return restDay;
	}
}


//var config = {
//	//		colorArray:['Blue','#8B2500','LightPink','Crimson','Purple','SkyBlue','Aqua','Green','LawnGreen','#FF6EB4','GoldEnrod','#B23AEE','OrangeRed','LightGreen', '#8B0000','#AB82FF','#FFBBFF','#FF34B3','#CD1076','#FFE7BA','#FFEC8B','#53868B','#6495ED','#ADFF2F','#F5F5DC','#A020F0','#C6E2FF','#7A8B8B']
//	colorArray: ['rgb(0,0,0)', 'rgb(43,108,40)', 'rgb(152,32,15)', 'rgb(47,117,181)', 'rgb(56,152,14)', 'rgb(112,48,160)', 'rgb(91,155,213)', 'rgb(237,125,49)', 'rgb(123,123,123)', 'rgb(192,0,0)', 'rgb(30,30,30)', 'rgb(38,103,37)', 'rgb(225,30,13)', 'rgb(40,112,225)', 'rgb(50,175,25)', 'rgb(195,48,130)', 'rgb(85,150,205)', 'rgb(245,100,45)', 'rgb(40,40,80)', 'rgb(255,0,0)', 'rgb(0,255,0)', 'rgb(0,0,255)', 'rgb(200,25,10)', 'rgb(35,108,210)', 'rgb(45,195,35)', 'rgb(465,90,145)', 'rgb(70,145,215)', 'rgb(45,225,150)', 'rgb(180,180,180)', 'rgb(50,50,50)']
//}